package com.atguigu.consumer;

import com.atguigu.constant.MqConst;
import com.atguigu.service.SearchService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class EsConsumer {
    @Autowired
    private SearchService searchService;
    //接受上架的消息
    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = MqConst.ON_SALE_QUEUE,durable = "false"),
    exchange = @Exchange(value = MqConst.ON_OFF_SALE_EXCHANGE,durable = "false"),
    key = {MqConst.ON_SALE_ROUTING_KEY}))
    public void onSale(Long skuId, Channel channel, Message message) throws IOException {//可直接获取到传入的消息(注意:消息名称要与传入的一致  不然获取不到)
        if (skuId != null){
            searchService.onSale(skuId);
        }
        //商品上架消费完成后 在进行手动的签收
        //DeliveryTag 代表签收那个消息   Boolean multiple 代表是否确认多个消息 false 则为签收当前的消息
        //channel.basicReject(basicReject 为拒收 接收端在发送reject命令的时候可以选择是否要重新放回queue中)
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
    //接受下架的消息
    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = MqConst.OFF_SALE_QUEUE,durable = "false"),
    exchange = @Exchange(value = MqConst.ON_OFF_SALE_EXCHANGE,durable = "false"),
    key = {MqConst.OFF_SALE_ROUTING_KEY}))
    public void offSale(Long skuId, Channel channel, Message message) throws IOException {//可直接获取到传入的消息(注意:消息名称要与传入的一致  不然获取不到)
        if (skuId != null){
            searchService.offSale(skuId);
        }
        //商品上架消费完成后 在进行手动的签收
        //DeliveryTag 代表签收那个消息   Boolean multiple 代表是否确认多个消息 false 则为签收当前的消息
        //channel.basicReject(basicReject 为拒收 接收端在发送reject命令的时候可以选择是否要重新放回queue中)
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
